import os
import importlib
import sys

def list_projects():
    """列出所有可用的项目"""
    projects = []
    base_dir = os.path.dirname(os.path.abspath(__file__))
    projects_dir = os.path.join(base_dir, 'projects')
    
    if not os.path.exists(projects_dir):
        return projects
    
    for item in os.listdir(projects_dir):
        project_dir = os.path.join(projects_dir, item)
        if os.path.isdir(project_dir) and (os.path.exists(os.path.join(project_dir, 'main.py') ) or os.path.exists(os.path.join(project_dir,'app.py')) ):
            projects.append(item)
            
    
    return sorted(projects)

def run_project(project_name):
    """运行指定的项目"""
    import multiprocessing
    base_dir = os.path.dirname(os.path.abspath(__file__))
    project_dir = os.path.join(base_dir, 'projects', project_name)
    
    if not os.path.exists(project_dir):
        print(f"错误：项目 '{project_name}' 不存在")
        return
    
    # 检查main.py或app.py是否存在
    project_main = os.path.join(project_dir, 'main.py')
    project_app = os.path.join(project_dir, 'app.py')
    
    if not os.path.exists(project_main) and not os.path.exists(project_app):
        print(f"错误：项目 '{project_name}' 的main.py或app.py文件都不存在")
        return
    
    def run_flask_app(project_dir):
        # 将项目目录添加到Python路径
        sys.path.insert(0, project_dir)
        try:
            project_module = importlib.import_module('app')
            if hasattr(project_module, 'app'):
                print(f"Flask应用已启动，请访问 http://localhost:5000")
                project_module.app.run(debug=True, use_reloader=False)
            else:
                print(f"错误：项目的app.py文件中没有app对象")
        except Exception as e:
            print(f"运行Flask应用时发生错误：{str(e)}")
        finally:
            sys.path.pop(0)
    
    def run_main_module(project_dir):
        # 将项目目录添加到Python路径
        sys.path.insert(0, project_dir)
        try:
            project_module = importlib.import_module('main')
            if hasattr(project_module, 'main'):
                project_module.main()
            else:
                print(f"错误：项目的main.py文件中没有main()函数")
        except Exception as e:
            print(f"运行项目时发生错误：{str(e)}")
        finally:
            sys.path.pop(0)
    
    try:
        if os.path.exists(project_main):
            # 运行普通Python项目
            run_main_module(project_dir)
        else:
            # 直接运行Flask应用
            run_flask_app(project_dir)
    except Exception as e:
        print(f"运行项目 '{project_name}' 时发生错误：{str(e)}")

def main():

    
    """主程序入口"""
    while True:
        print("\n=== Python教学项目集合 ===")
        print("1. 列出所有项目")
        print("2. 运行项目")
        print("3. 退出")
        
        choice = input("\n请选择操作 (1-3): ")
        
        if choice == '1':
            projects = list_projects()
            if projects:
                print("\n可用的项目：")
                for i, project in enumerate(projects, 1):
                    print(f"{i}. {project}")
            else:
                print("\n当前没有可用的项目")
                
        elif choice == '2':
            projects = list_projects()
            if not projects:
                print("\n当前没有可用的项目")
                continue
                
            print("\n可用的项目：")
            for i, project in enumerate(projects, 1):
                print(f"{i}. {project}")
                
            try:
                project_index = int(input("\n请选择要运行的项目编号: ")) - 1
                if 0 <= project_index < len(projects):
                    run_project(projects[project_index])
                else:
                    print("无效的项目编号")
            except ValueError:
                print("请输入有效的数字")
                
        elif choice == '3':
            print("\n感谢使用！再见！")
            break
            
        else:
            print("\n无效的选择，请重试")

if __name__ == '__main__':
    main()